#pragma once
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

// 蓝牙串口服务和特征
#define SERVICE_UUID        "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"

// 蓝牙串口类
class BluetoothSerial {
public:
    BluetoothSerial();
    ~BluetoothSerial();
    
    // 初始化蓝牙
    void begin(const char* deviceName);
    
    // 检查是否有数据可读
    bool available();
    
    // 读取数据
    uint8_t read();
    
    // 写入数据
    void write(uint8_t data);
    void write(const uint8_t* data, size_t length);
    
    // 打印字符串
    void print(const char* data);
    void println(const char* data);
    
    // 检查是否已连接
    bool isConnected();
    
private:
    // 蓝牙服务器和特征
    BLEServer* pServer;
    BLECharacteristic* pTxCharacteristic;
    BLECharacteristic* pRxCharacteristic;
    
    // 连接状态
    bool deviceConnected;
    
    // 接收缓冲区
    static const int RX_BUFFER_SIZE = 256;
    uint8_t rxBuffer[RX_BUFFER_SIZE];
    int rxBufferHead;
    int rxBufferTail;
    
    // 静态回调函数
    static void onConnect(BLEServer* pServer);
    static void onDisconnect(BLEServer* pServer);
    static void onWrite(BLECharacteristic* pCharacteristic);
    
    // 友元类声明，允许回调函数访问私有成员
    friend class BluetoothSerialCallbacks;
    friend class BluetoothSerialRxCallbacks;
};